#include <QtGui/QApplication>
#include <QTextCodec>
#include <QMessageBox>
#include <QPushButton>

#include <QLabel>
#include <QFontDatabase>

#include "pisplayer.h"
#include "flashplayer/flashplayer.h"

#include "log4qt/propertyconfigurator.h"
#include "log4qt/log4qt.h"
#include "log4qt/consoleappender.h"
#include "log4qt/logger.h"
#include "log4qt/ttcclayout.h"
#include "log4qt/fileappender.h"
#include "qfileinfo.h"

#include "public/environment.h"
#include "public/configclass.h"
#include "public/processsignalobject.h"
#include "licence/licence.h"

//#define LICENSE
//LINUX下为应用程序的路径
//CE 下为应用程序的路径



QString g_installPath;

QString g_NotePath;

//CE 下为创建资源工程的路径
QString g_AppPath;

Debug_Config_s g_stDebugConfig;

//防止程序被启动两次
#if defined Q_OS_WIN32   //for win
#include <windows.h>
bool checkOnly(const QString& filePath)
{
    char fileBuf[128];
    QString fileName ="lockfile";
    strcpy(fileBuf, fileName.toLatin1().data());
    //  创建互斥量
    HANDLE m_hMutex  =  CreateMutex(NULL, FALSE,  fileBuf);
    //  检查错误代码
    if  (GetLastError()  ==  ERROR_ALREADY_EXISTS)
    {
        //  如 果已有互斥量存在则释放句柄并复位互斥量
        CloseHandle(m_hMutex);
        m_hMutex  =  NULL;
        //  程序退出
        return  false;
    }
    else
        return true;
}
#endif

#ifdef Q_OS_UNIX   //for linux
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
bool checkOnly(const QString& filePath, int *fd)
{
    char fileBuf[256];
    QString fileName = ".lockfile";
    strcpy(fileBuf, fileName.toLatin1().data());
//    qDebug() << filePath << "fileBUf...........>" << fileBuf;
    *fd = open (fileBuf, O_WRONLY | O_CREAT , 0755);
    int flock = lockf(*fd, F_TLOCK, 0);
    if (*fd == -1) {
            perror("can't open lockfile\n");
            return false;
    }
    //给文件加锁
    if (flock == -1) {
            perror("lock file error\n");
            return false;
    }
    //程序退出后，文件自动解锁
    return true;
}
#endif


int main(int argc, char *argv[])
{
    //argv[1]资源工程路径 argv[2]资源工程名字 argv[3]应用程序名字
#ifdef Q_OS_UNIX
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
    QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
#endif


    QApplication::addLibraryPath("./plugins");

    QApplication a(argc, argv);

    a.setApplicationName("PisPlay");

    QApplication::addLibraryPath(QObject::tr("%1/plugins").arg(QCoreApplication::applicationDirPath()));


#ifdef Q_OS_WIN32
    g_installPath = QCoreApplication::applicationDirPath();
#else Q_OS_UNIX
#ifdef Q_OS_MAC
    g_installPath = QObject::tr("/Users/mac-lin/Documents/project/Qt/build-PISPlayer-桌面-Debug/");
#else Q_OS_LINUX
    g_installPath = QCoreApplication::applicationDirPath();
#endif
#endif

    int fd;


#ifdef _TTY_POSIX_
    //检查程序是否 已经启动过
    if(checkOnly(g_installPath, &fd) == false)
        return 0;
#else
    //检查程序是否 已经启动过
    if(checkOnly(g_installPath) == false)
        return 0;
#endif


    QString updateState = "0";
    Configclass configclass;

    g_stDebugConfig.isDebugSerialPort = configclass.getDebugSerialPort();
    g_stDebugConfig.isDebugTisCtl     = configclass.getDebugTisCtl();


#ifdef CEPIDS
    g_installPath = argv[1];
    g_installPath.replace("\\", "/");
    QString proName = argv[2];
    Configclass configclass;
    configclass.setScheduleProName(proName);
    configclass.sync();
    g_AppPath = argv[3];
    g_AppPath.replace("\\", "/");
//    g_installPath = "E:/project/Qt/PISPlayer-build-desktop/release";

    QFont f;

#else
    if (argc > 1)
    {
        updateState = argv[1];
    }

    QFont f(configclass.getSysFont());
#endif


    f.setPixelSize(14);
    a.setFont(f);

#ifdef LICENSE
    //检查licese是否正确
    QString msg;
    licence lice;

    if (!lice.checkLicence(msg))
    {
        return -1;
    }
#endif

    Log4Qt::PropertyConfigurator::configure(a.applicationDirPath() + "/log4j.properties");
//    qDebug() << "QT_Verison is less 4.7, current version is" << QT_VERSION_STR;

    PISPlayer w(updateState);
    w.show();

    //实现重启功能
    int ret = a.exec();
    if (ret == 773)
    {
        QProcess::startDetached(qApp->applicationFilePath());
        return 0;
    } else if (ret == 222)
    {
#ifdef _TTY_POSIX_
        lockf(fd, F_ULOCK, 0);
        close(fd);
#endif
        return 0;
    }

    return ret;
}
